package com.zhuhao.basic.proxy.jdk;

import com.zhuhao.basic.proxy.jdk.goal.classtarget.HelloService;
import com.zhuhao.basic.proxy.jdk.goal.classtarget.HelloServiceImpl;
import com.zhuhao.basic.proxy.jdk.goal.interfacetarget.User;
import com.zhuhao.basic.proxy.jdk.goal.interfacetarget.UserMapper;
import org.junit.Test;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 生成代理对象
 * @Author haozhu7
 * @Date 2025/5/22 15:03
 **/
public class JDKProxyExample {

    /**
     * 目标对象是一个类（需要实现一个接口）通过代理进行增强
     */
    @Test
    public void classTargetProxyTest() {
        //目标对象
        HelloService target = new HelloServiceImpl();

        //生成代理对象
        HelloService proxy = (HelloService) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                //目标接口，可以是个数组
                target.getClass().getInterfaces(),
                //代理对象
                new MyInvocationHandler(target)
        );

        //目标接口被代理吗，调用任意方法都是触发代理逻辑(接口的默认实现也会被代理)
        String s = proxy.sayHello("小明");
        System.out.println(s);

        System.out.println(proxy.sayHello2("小明"));
        System.out.println(proxy.sayHello3("小明"));
        System.out.println(proxy.sayHello4("小明"));
    }


    /**
     * 目标对象是一个接口
     */
    @Test
    public void targetNoImplProxyTest() {
        //生成代理对象
        UserMapper proxy = (UserMapper) Proxy.newProxyInstance(
                UserMapper.class.getClassLoader(),
                new Class[]{UserMapper.class},
                new MyInvocationHandler(null)
        );

        //这里是模拟mybatis的mapper接口
        List<User> userList = proxy.queryAll("小明", 18, null);
        userList.forEach(System.out::println);
    }
}